#!/bin/sh
#
# Run from crontab to fetch new editions of online newspapers
# and expire old editions of online newspapers.
# 

# Find the directory this script resides in.
SCRIPTDIR=`(cd $(dirname $0); pwd)`

# Create an http://nrk.no cover image (takes approx 1 minute)
$SCRIPTDIR/create_nrk_cover_image

# Variables that may need adjustment
RECIPE_LIST="nrk.recipe vg.recipe aftenposten.recipe"
expirationDate=`date --date "2 days ago" "+%s"`

# Locations recipes, epub files and the calibre database
# Note: RECIPEDIR is the same directory this script resides in
RECIPEDIR=`(cd $(dirname $0); pwd)`
IMPORTDIR=/tmp/avis
EPUBFILE=$IMPORTDIR/avis.epub
MOBIFILE=`echo $EPUBFILE | sed 's/\.epub$/.mobi/g'`
LIBRARY_LOCATION=$HOME/aviser
LOG_FILE=/dev/null
#LOG_FILE=/tmp/update_news.log

#
# First fetch the current editions of the online newspapers.
#
echo "Log file for calibre newspaper update script" >$LOG_FILE
cd $RECIPEDIR
for recipe in $RECIPE_LIST;do
    publicationName=`echo $recipe | sed 's/\.recipe$//g'`
    mkdir -p $IMPORTDIR
    ebook-convert $recipe $EPUBFILE --output-profile=sony --tags News,$publicationName --preserve-cover-aspect-ratio >>$LOG_FILE
    ebook-convert $EPUBFILE $MOBIFILE --mobi-file-type new >>$LOG_FILE 2>&1
    calibredb add -d --with-library $LIBRARY_LOCATION --one-book-per-directory $IMPORTDIR >>$LOG_FILE
    rm -rf $IMPORTDIR
done


#
# Expire newspaper editions older than expireDate (set at the start of the script).
#

# Setting the bash Internal Field Separator to a line shift,
# causes calibredb output to be read line by line in the for loop.
IFS="
"

for line in `calibredb list --with-library $LIBRARY_LOCATION -f pubdate`;do
  # Avoid processing the header line.
  lineStrippedOfTrailingSpc=`echo $line | sed 's/ *$//g' | tr -s " "`
  if [ "id pubdate" != "$lineStrippedOfTrailingSpc" ];then
      id=`echo $line | sed 's/^\([0-9]\+\) .*/\1/g'`
      pubdate=`echo $line | sed 's/^\([0-9]\+\) \(.*\)/\2/g' | tr "T" " "`
      pubdateAsSeconds=`date --date $pubdate "+%s"`
      if [ "$pubdateAsSeconds" -lt "$expirationDate" ]; then
          # Expiring article older than the expirationDate
          calibredb remove $id --with-library $LIBRARY_LOCATION >>$LOG_FILE
      fi
  fi
done

# After expiry, empty the Gnome trashcan (where calibre drops the
# expired newspapers)
#
# Use the trash-cli tools if available ("rm -rf" in the appropriate
# directory would also do the trick, but the tools know where "the
# appropriate directory" is).
#
TRASH_EMPTY=/usr/bin/trash-empty
if [ -x "$TRASH_EMPTY" ]; then
    echo "Disk usage before cleanup:" >>$LOG_FILE
    df >>$LOG_FILE
    $TRASH_EMPTY >>$LOG_FILE
    echo "Disk usage after cleanup:" >>$LOG_FILE
    df >>$LOG_FILE
fi
